package com.hcloud.auth.handler;

import com.hcloud.common.core.base.HCloudResult;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * 获取token时的错误转义
 *
 * @Auther hepangui
 * @Date 2018/11/12
 */
@Component
public class HcloudOAuthExceptionTranslator implements WebResponseExceptionTranslator {

    @Override
    public ResponseEntity translate(Exception e) throws Exception {
        String msg = e.getMessage();
        if (e instanceof UnsupportedGrantTypeException) {
            msg = "错误的认证方式";
        } else if (e instanceof InvalidGrantException) {
            if (e.getMessage() != null && e.getMessage().equals("坏的凭证")) {
                msg = "用户名或密码错误";
            } else {
                msg = e.getMessage();
            }
        }else if(e instanceof InternalAuthenticationServiceException){
            msg = "用户名或密码错误";
        }
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        HCloudResult hcloudResult = new HCloudResult(msg);
        return new ResponseEntity(hcloudResult, headers, HttpStatus.OK);
    }
}
